package com.leinardi.ohos.speeddial.sample.slice;

import com.leinardi.ohos.speeddial.sample.ResourceTable;
import com.leinardi.ohos.speeddial.*;
import com.leinardi.ohos.speeddial.sample.*;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.components.element.PixelMapElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.utils.TextTool;
import ohos.agp.window.dialog.PopupDialog;
import ohos.agp.window.dialog.ToastDialog;
import ohos.global.resource.NotExistException;

import java.io.IOException;
import java.util.List;

public class MainAbilitySlice extends AbilitySlice {
    private static final int ADD_ACTION_POSITION = 4;

    private SpeedDialView mSpeedDialView;

    private ToastDialog mToast;

    private ListContainer mListContainer;

    private CustomAdapter mProvider;

    private SnackBar mSnackBar;

    private boolean isIdle = true;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        try {
            UiUtils.setStatusBarColor(UiUtils.getColor(this, ResourceTable.Color_inbox_primary_dark));
            initSpeedDialView();
            initListener();
            initListContainer();
        } catch (NotExistException | IOException e) {
            e.printStackTrace();
        }
    }

    private void initSpeedDialView() throws NotExistException, IOException {
        mSpeedDialView = (SpeedDialView) findComponentById(ResourceTable.Id_SpeedDialView);

        mSpeedDialView.addActionItem(new SpeedDialActionItem.Builder(ResourceTable.Integer_fab_no_label, ResourceTable.Graphic_ic_link_white_24dp)
                .create());

        PixelMapElement element = new PixelMapElement(getResourceManager().getResource(ResourceTable.Media_ic_custom_color));
        FabWithLabelView fabWithLabelView = mSpeedDialView.addActionItem(new SpeedDialActionItem.Builder(ResourceTable.Integer_fab_custom_color, element)
                .setFabImageTintColor(ResourceTable.Color_inbox_primary)
                .setLabel(ResourceTable.String_label_custom_color)
                .setLabelColor(Color.WHITE.getValue())
                .setLabelBackgroundColor(UiUtils.getColor(getContext(), ResourceTable.Color_inbox_primary))
                .create());

        SpeedDialActionItem mActionItem = fabWithLabelView.getSpeedDialActionItemBuilder().setFabBackgroundColor(UiUtils.getColor(this, ResourceTable.Color_material_white_1000)).create();
        fabWithLabelView.setSpeedDialActionItem(mActionItem);

        PixelMapElement element2 = new PixelMapElement(getResourceManager().getResource(ResourceTable.Media_ic_lorem_ipsum));
        mSpeedDialView.addActionItem(new SpeedDialActionItem.Builder(ResourceTable.Integer_fab_long_label, element2)
                .setFabSize(FloatingActionButton.SIZE_NORMAL)
                .setLabel("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor " +
                          "incididunt ut labore et dolore magna aliqua.")
                .create());

        mSpeedDialView.addActionItem(new SpeedDialActionItem.Builder(ResourceTable.Integer_fab_add_action, ResourceTable.Graphic_ic_add_white_24dp)
                .setFabBackgroundColor(UiUtils.getColor(getContext(), ResourceTable.Color_material_green_500))
                .setLabel(ResourceTable.String_label_add_action)
                .setLabelBackgroundColor(Color.TRANSPARENT.getValue())
                .create());

        mSpeedDialView.addActionItem(new SpeedDialActionItem.Builder(ResourceTable.Integer_fab_custom_theme, ResourceTable.Graphic_ic_theme_white_24dp)
                .setFabBackgroundColor(UiUtils.getColor(getContext(), ResourceTable.Color_material_purple_500))
                .setLabel(getString(ResourceTable.String_label_custom_theme))
                .create());

        mSpeedDialView.setOnChangeListener(new SpeedDialView.OnChangeListener() {
            @Override
            public boolean onMainActionSelected() {
                showToast("Main action clicked!");
                return false;
            }

            @Override
            public void onToggleChanged(boolean isOpen) {

            }
        });

        mSpeedDialView.setOnActionSelectedListener(actionItem -> {
            switch (actionItem.getId()) {
                case ResourceTable.Integer_fab_no_label:
                    showToast("No label action clicked!\nClosing with animation");
                    mSpeedDialView.close();
                    return true;
                case ResourceTable.Integer_fab_long_label:
                    showSnackBar(actionItem.getLabel(this) + " clicked!");
                    break;
                case ResourceTable.Integer_fab_custom_color:
                    showToast(actionItem.getLabel(this) + " clicked!\nClosing without animation.");
                    return false;
                case ResourceTable.Integer_fab_custom_theme:
                    showToast(actionItem.getLabel(this) + " clicked!");
                    break;
                case ResourceTable.Integer_fab_add_action:
                    mSpeedDialView.addActionItem(new SpeedDialActionItem.Builder(ResourceTable.Integer_fab_replace_action,
                            ResourceTable.Graphic_ic_replace_white_24dp)
                            .setFabBackgroundColor(UiUtils.getColor(this, ResourceTable.Color_material_orange_500))
                            .setLabel(getString(ResourceTable.String_label_replace_action))
                            .create(), ADD_ACTION_POSITION);
                    break;
                case ResourceTable.Integer_fab_replace_action:
                    mSpeedDialView.replaceActionItem(new SpeedDialActionItem.Builder(ResourceTable.Integer_fab_remove_action, ResourceTable.Graphic_ic_delete_white_24dp)
                            .setLabel(getString(ResourceTable.String_label_remove_action))
                            .setFabBackgroundColor(UiUtils.getColor(this, ResourceTable.Color_inbox_accent))
                            .create(), ADD_ACTION_POSITION);
                    break;
                case ResourceTable.Integer_fab_remove_action:
                    mSpeedDialView.removeActionItemById(ResourceTable.Integer_fab_remove_action);
                    break;
                default:
                    break;
            }
            return true;
        });
    }

    private void initListener() {
        findComponentById(ResourceTable.Id_showLayout).setClickedListener(component -> {
            if(isIdle) {
                if (mSpeedDialView.getVisibility() == Component.VISIBLE) {
                    mSpeedDialView.hide();
                } else {
                    mSpeedDialView.show();
                }
            }
        });

        findComponentById(ResourceTable.Id_snackLayout).setClickedListener(component -> {
            showSnackBar("Test snackbar");
        });

        findComponentById(ResourceTable.Id_expansionLayout).setClickedListener(component -> {
            showPopMenu(component, MenuInfoConstants.expandModeList, "");
        });

        findComponentById(ResourceTable.Id_rotationLayout).setClickedListener(component -> {
            showPopMenu(component, MenuInfoConstants.rotateDegreeList, "");
        });

        findComponentById(ResourceTable.Id_moreLayout).setClickedListener(component -> {
            showPopMenu(component, MenuInfoConstants.moreList, "");
        });
    }

    private void initListContainer() {
        mListContainer = (ListContainer) findComponentById(ResourceTable.Id_listContainer);
        mProvider = new CustomAdapter(this);
        mListContainer.setItemProvider(mProvider);

        mListContainer.addScrolledListener(new Component.ScrolledListener() {
            @Override
            public void onContentScrolled(Component component, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if(scrollY > oldScrollY) {
                    //上滑，消失
                    mSpeedDialView.hide();
                }else {
                    //下滑，显示
                    mSpeedDialView.show();
                }
            }

            @Override
            public void scrolledStageUpdate(Component component, int newStage) {
                isIdle = newStage == Component.SCROLL_IDLE_STAGE;
            }
        });
    }

    private void showToast(String msg) {
//        if(mToast != null) {
//            mToast.cancel();
//        }
        DirectionalLayout layout = (DirectionalLayout) LayoutScatter.getInstance(getContext())
                .parse(ResourceTable.Layout_layout_toast, null, false);
        Text text = (Text) layout.findComponentById(ResourceTable.Id_msg_toast);
        text.setText(msg);

        if(mToast == null) {
            mToast = new ToastDialog(getContext());
            mToast.setSize(DirectionalLayout.LayoutConfig.MATCH_CONTENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT);
            mToast.setAlignment(LayoutAlignment.BOTTOM);
            mToast.setOffset(0, AttrHelper.fp2px(50, this));
            mToast.setAutoClosable(true);
        }
        mToast.setContentCustomComponent(layout);
        mToast.show();
    }

    private void showSnackBar(String text) {
        if(mSnackBar != null) {
            mSnackBar.close(false);
        }
        mSnackBar = SnackBar.make(findComponentById(ResourceTable.Id_parent), text, SnackBar.LENGTH_SHORT);
        mSnackBar.setActionListener("CLOSE", component -> mSnackBar.close(true));
        mSnackBar.show();
    }

    private void showPopMenu(Component archComponent, List<MenuInfo> menuInfoList, String title) {
        PopupDialog popupDialog = new PopupDialog(this, archComponent);

        Component component = LayoutScatter.getInstance(this).parse(ResourceTable.Layout_popmenu_layout, null, false);
        ListContainer listContainer = (ListContainer) component.findComponentById(ResourceTable.Id_listContainer);
        listContainer.setEnabled(false);
        listContainer.setItemClickedListener(new ListContainer.ItemClickedListener() {
            @Override
            public void onItemClicked(ListContainer listContainer, Component component, int position, long id) {
                if(id == ResourceTable.Integer_action_toggle_list) {
                    if (mListContainer.getItemProvider() == null) {
                        mListContainer.setItemProvider(mProvider);
                    } else {
                        mListContainer.setItemProvider(null);
                        mListContainer.invalidate();
                        if (mSpeedDialView.getVisibility() != Component.VISIBLE) {
                            mSpeedDialView.show();
                        }
                    }
                }else if(id == ResourceTable.Integer_action_main_fab_color) {
                    showPopMenu(archComponent, MenuInfoConstants.mainFabColorList, "Main FAB color");
                }else if(id == ResourceTable.Integer_action_main_fab_background_color_open) {
                    showPopMenu(archComponent, MenuInfoConstants.mainFabOpenColorList, "Main FAB color open");
                }else if(id == ResourceTable.Integer_action_main_fab_background_color_close) {
                    showPopMenu(archComponent, MenuInfoConstants.mainFabCloseColorList, "Main FAB color close");
                }else {
                    MenuUtils.handlerMenuSetting(mSpeedDialView, id);
                }
                popupDialog.hide();
            }
        });
        listContainer.setItemProvider(new MenuAdapter(this, menuInfoList));

        Text mTitleText = (Text) component.findComponentById(ResourceTable.Id_title);
        if(TextTool.isNullOrEmpty(title)) {
            mTitleText.setVisibility(Component.HIDE);
        }else {
            mTitleText.setVisibility(Component.VISIBLE);
            mTitleText.setText(title);
        }

        popupDialog.setCustomComponent(component);
        popupDialog.setHasArrow(false);
        popupDialog.setAutoClosable(true);
        popupDialog.setOffset(0, -80);
        popupDialog.show();
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
